/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */
import { spawnSync } from 'child_process';

import { OhosLogger } from './log/ohos-logger';

const isWindows = process.platform === 'win32';
const scriptShell = isWindows ? process.env.ComSpec || 'cmd' : process.env.SHELL || 'sh';

const _log: OhosLogger = OhosLogger.getLogger('OhPackageLoader');

export class RunCommandUtil {
  public static run(script: string, cwd: string = process.cwd(), printLog: boolean): boolean {
    if (!script) {
      _log.error('', `Missing script: ${script}`);
      return false;
    }

    // /d: cmd 中禁用自动运行命令。
    // /s: cmd 用于处理引号内的命令。
    // /c: cmd 执行字符串指定的命令然后终止。
    // -c: shell 中执行字符串指定的命令然后终止。
    // 拼接参数并执行
    const spawnArgs = isWindows ? ['/d', '/c', script] : ['-c', script];

    // execute script
    const result = spawnSync(scriptShell, spawnArgs, {
      windowsVerbatimArguments: true,
      stdio: 'inherit',
      cwd,
      env: process.env,
    });

    // 成功
    if (result && result.status === 0) {
      return true;
    }

    // 打印失败日志详情
    if (printLog) {
      const error = result.error?.message;
      _log.warn(`excute command failed, error is${error}`);
    }
    return false;
  }
}
